import 'package:fish_redux/fish_redux.dart';
import 'action.dart';
import 'state.dart';
import '../../../app_files.dart';
import '../model/order_view_model.dart';

Effect<SafeOrderViewState> buildEffect() {
  return combineEffects(<Object, Effect<SafeOrderViewState>>{
    SafeOrderViewAction.action: _onAction,
    SafeOrderViewAction.onTapSign: _onTapSign,
    SafeOrderViewAction.onTapOrderPic: _onTapOrderPic,
    SafeOrderViewAction.onTapResultPic: _onTapResultPic,
    Lifecycle.initState: _initState,
  });
}

void _onAction(Action action, Context<SafeOrderViewState> ctx) {}

void _initState(Action action, Context<SafeOrderViewState> ctx) async {
  await Future.delayed(Duration(milliseconds: 300));
  ResultData res = await CommonNetWork.safeOrderDetail(ctx.state.gasNo);
  if (res.success) {
    ctx.dispatch(SafeOrderViewActionCreator.onGetData(res.data));
  } else {
    if (res.desc == '还未进行过安检') {
      ctx.dispatch(SafeOrderViewActionCreator.onGetData(null));
    } else
      CommonUtils.showErrorInfo(ctx.context, res.desc);
  }
}

void _onTapSign(Action action, Context<SafeOrderViewState> ctx) async {
  List<GalleryExampleItem> items = [
    GalleryExampleItem(
      id: '0',
      resource: ctx.state.orderSignPhoto,
    )
  ];
  items = await CommonUtils.showPhotoAlbumView(
    ctx.context,
    initialIndex: 0,
    galleryItems: items,
  );
}

void _onTapOrderPic(Action action, Context<SafeOrderViewState> ctx) async {
  var file = action.payload;
  List<GalleryExampleItem> items = ctx.state.orderPhoto.map((e) {
    int index = ctx.state.orderPhoto.indexOf(e);
    return GalleryExampleItem(
      id: '$index',
      resource: e,
    );
  }).toList();
  items = await CommonUtils.showPhotoAlbumView(
    ctx.context,
    initialIndex: ctx.state.orderPhoto.indexOf(file),
    galleryItems: items,
  );
}

void _onTapResultPic(Action action, Context<SafeOrderViewState> ctx) async {
  OrderConfigModel model = action.payload['model'];
  var file = action.payload['data'];
  List<GalleryExampleItem> items = model.imageList.map((e) {
    int index = model.imageList.indexOf(e);
    return GalleryExampleItem(
      id: '$index',
      resource: e,
    );
  }).toList();
  items = await CommonUtils.showPhotoAlbumView(
    ctx.context,
    initialIndex: model.imageList.indexOf(file),
    galleryItems: items,
  );
}
